# -*- coding: utf-8 -*-
from pyhost.sha1storage.models import SHA1FilesRealname
from django.core.files.storage import FileSystemStorage
from hashlib import sha1
import os.path
from django.conf import settings

ACCEL_ROOT = getattr(settings, 'ACCEL_ROOT', "sha1storage")

class SHA1FilenameFileSystemStorage(FileSystemStorage):
	def _save(self, name, content):
		dir_name, file_name = os.path.split(name)
		file_root, file_ext = os.path.splitext(file_name)
		hashed_name = self.hash_name(file_name)
		hashed_path = self.get_real_available_name(os.path.join(ACCEL_ROOT, dir_name, hashed_name))
		super(SHA1FilenameFileSystemStorage, self)._save(hashed_path, content)
		realname = SHA1FilesRealname(realname=hashed_path, username=name)
		realname.save()
		return name
	
	def _open(self, name,  mode='rb'):
		try:
			realname = SHA1FilesRealname.objects.get(username=name)
			return super(SHA1FilenameFileSystemStorage, self)._open(realname.realname,  mode)
		except:
			return super(SHA1FilenameFileSystemStorage, self)._open(name,  mode)
	
	def delete(self, name):
		
		try:
			realname = SHA1FilesRealname.objects.get(username=name)
			name = realname.realname
			realname.delete()
		except:
			pass
		return super(SHA1FilenameFileSystemStorage, self).delete(name)
	
	def hash_name(self, name):
		return str(sha1(name.encode("UTF-8")).hexdigest())
	
	def get_real_available_name(self, name):
		return super(SHA1FilenameFileSystemStorage, self).get_available_name(name)

	def get_available_name(self, name):
		dir_name, file_name = os.path.split(name)
		file_root, file_ext = os.path.splitext(file_name)
		clear = False
		while not clear:
			try:
				file_root += '_'
				realname = SHA1FilesRealname.objects.get(username=name)
				name = os.path.join(dir_name, file_root + file_ext)
			except:
				clear = True
				
		return name
	
	def path(self, name):
		try:
			realname = SHA1FilesRealname.objects.get(username=name)
			return super(SHA1FilenameFileSystemStorage, self).path(realname.realname)
		except:
			return super(SHA1FilenameFileSystemStorage, self).path(name)
	
